package com.spring.springboot.Service;

import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.spring.springboot.entity.GoodInfoEntity;
import com.spring.springboot.entity.GoodTypeEntity;
import com.spring.springboot.jpa.GoodJPA;
import com.spring.springboot.jpa.TypeJPA;

/**
*@author LSY
*Time: 2018年12月12日下午5:06:14
*
*
*/
@Service
@CacheConfig(cacheNames = "user")
public class GoodService {

	private static Logger logger = LoggerFactory.getLogger(GoodService.class);
	@Autowired
	private TypeJPA typeJPA;
	
	@Autowired
	private GoodJPA goodJPA;
	
	@Cacheable
	public List<GoodTypeEntity> findAll(){
		return typeJPA.findAll();
	}
	
	@Cacheable(value = "thisredis", key = "'good_' + #id")
	public GoodInfoEntity findById(Long id){
		Optional<GoodInfoEntity>op = goodJPA.findById(id);
		GoodInfoEntity info = null;
		try {
			info = op.get();
		} catch(NoSuchElementException e) {
			logger.error("id 不存在");
			return info;
		} catch (Exception e) {
			return info;
		}
		return op.get();
	}
	
	@CacheEvict(value = "thisredis", key ="'good_' + #id", condition = "#id != 1")
	public void delGood(Long id) {
		try {
			goodJPA.deleteById(id);
		} catch(NoSuchElementException e) {
			logger.error("id 不存在");
		} catch (Exception e) {
			logger.error("====id " + e.toString());
		}
		
	}
}
